package com.meitianhui.convenitenbuy.module.order.ui.fragment;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseFragment;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.home.ui.activity.SubmitOrderActivity;
import com.meitianhui.convenitenbuy.module.order.adapter.HuiGuoOrderAdapterTest;
import com.meitianhui.convenitenbuy.module.order.contract.EdinburghTypeOrderContract;
import com.meitianhui.convenitenbuy.module.order.di.DaggerOrderComponent;
import com.meitianhui.convenitenbuy.module.order.di.OrderModule;
import com.meitianhui.convenitenbuy.module.order.model.bean.OrderInfo;
import com.meitianhui.convenitenbuy.module.order.presenter.EdinburghTypeOrderPresenter;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.CancelOrderDialog;
import com.meitianhui.convenitenbuy.widget.dialog.ConfirmOrderDialog;
import com.meitianhui.convenitenbuy.widget.dialog.LoadingDialog;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by amy on 2018/1/13.
 */

public class HuiGuoOrderTypeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,  EdinburghTypeOrderContract.View{

    private String mService = "order.consumer.fgOrderListByHuiguoPageFind";
    private SwipeRefreshLayout mSwipeLayout;
    private RecyclerView mRecyclerView;
    private View mNotDataView;
    private String mStatus = "";
    private int mPageIndex = 1;
    private int mPageSize = 15;
    private CancelOrderDialog mCancelDialog;
    private int mOrderStatus = 0;   //0 取消订单  1 提交订单
    @Inject
    EdinburghTypeOrderPresenter presenter;
    private HuiGuoOrderAdapterTest mAdapter;
    private LoadingDialog mDialog;
    private ConfirmOrderDialog mConfirmDialog;

    @Override
    protected int getLayout() {
        return R.layout.fragment_huiguo_order_type;
    }

    @Override
    protected void initView(LayoutInflater inflater) {
        super.initView(inflater);
        DaggerOrderComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .orderModule(new OrderModule(this))
                .build()
                .inject(this);
        mSwipeLayout = (SwipeRefreshLayout) getViewById(R.id.hg_type_swipe_layout);
        mSwipeLayout.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView) getViewById(R.id.hg_type_order_list);
        LinearLayoutManager mLinearManager = new LinearLayoutManager(getActivity());
        mLinearManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLinearManager);
        mNotDataView = getActivity().getLayoutInflater().inflate(R.layout.data_empty_order, (ViewGroup) mRecyclerView.getParent(), false);
        initData();
    }

    private void initData() {
        mStatus = getArguments().getString("status");
      //  mAdapter = new HuiGuoOrderAdapter(getActivity(), null, null);

        mAdapter = new HuiGuoOrderAdapterTest(getActivity(), null, null, new HuiGuoOrderAdapterTest.OnClickOrder(){

            @Override
            public void cancelClick(String orderId) {
                mCancelDialog = new CancelOrderDialog(getActivity(), new CancelOrderDialog.DialogClick() {
                    @Override
                    public void cancelClick() {

                        mCancelDialog.stopProgressDialog();
                    }

                    @Override
                    public void submitClick() {
                        mOrderStatus = 0;
                        String account = mCancelDialog.getAccount();
                        if (TextUtils.isEmpty(account)) {
                            TipUtils.showToast(App.getInstance(), "请输入取消订单的理由", 3);
                        } else {
                            presenter.orderOperation(orderId, "order.fgOrderCancelled", account, "", Constants.CUSTOM_APP);
                            mCancelDialog.stopProgressDialog();
                        }
                    }
                });
            }

            @Override
            public void confirmClick(String orderId) {
                mConfirmDialog = new ConfirmOrderDialog(getActivity(), new ConfirmOrderDialog.DialogClick() {
                    @Override
                    public void cancelClick() {
                        mConfirmDialog.stopProgressDialog();
                    }

                    @Override
                    public void submitClick() {
                      /*  mOrderStatus = 1;
                        String orderCode = mConfirmDialog.getInputOrder();
                        if (TextUtils.isEmpty(orderCode)) {
                            TipUtils.showToast(App.getInstance(), "请输入淘宝订单单号", 3);
                        } else if (orderCode.trim().length() < 16 || orderCode.trim().length() > 20) {
                            TipUtils.showToast(App.getInstance(), "请填写正确的淘宝订单号！", 3);
                        } else {
                            presenter.orderOperation(orderId, "order.fgOrderConfirm", "", orderCode, Constants.CUSTOM_APP);
                            mConfirmDialog.stopProgressDialog();
                        }*/
                    }
                });
            }

            @Override
            public void customerClick() {
                JumpUtil.jumpToChatActivity(getActivity());
            }

            @Override
            public void goToSubmitOrder(String value, String order_id) {
                Intent intent = new Intent(getActivity(), SubmitOrderActivity.class);
                intent.putExtra("value",value);

                intent.putExtra("from",order_id);
                getActivity().startActivity(intent);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        if(mDialog==null){
            mDialog = new LoadingDialog(getActivity());
        }
        onRefresh();
        registerEvent();
    }


    private void registerEvent() {
        Disposable subscribe = RxBus.get().toFlowable(EventBean.class).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean eventBean) throws Exception {
                if (eventBean.getType() == Constants.EVENT_TYPE_ORDER_OPERATION) {
                    onRefresh();
                } else if (eventBean.type == Constants.EVENT_TYPE_LOGIN_SUCCESS) {
                    onRefresh();
                }
            }
        });

        mCompositeDisposable.add(subscribe);
        Disposable subscribe1 = RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean payResultBean) throws Exception {
                if (payResultBean.result == Constants.PAY_RESULT_SUCCESS) {
                    onRefresh();
                }
            }
        });
        mCompositeDisposable.add(subscribe1);
    }


    @Override
    public void call(Object o) {

    }

    @Override
    public void onRefresh() {
        mPageIndex = 1;
        presenter.getOrder(mService, mPageIndex + "", mPageSize + "", "", mStatus);
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void getOrderSuccess(OrderInfo orderInfo) {
        mSwipeLayout.setRefreshing(false);
        if (mDialog != null) {
            mDialog.stopProgressDialog();
        }
        setData(mPageIndex, orderInfo.getList(), orderInfo.getDoc_url());
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPageIndex++;
                presenter.getOrder(mService, mPageIndex + "", mPageSize + "", "", mStatus);
            }
        }, mRecyclerView);
    }

    private void setData(int pageIndex, List data, Map<String, String> map) {
        final int size = data == null ? 0 : data.size();
        if (pageIndex == 1) {
            mAdapter.setNewData(data, map);
            if (size == 0) {
                mAdapter.setEmptyView(mNotDataView);
            }
        } else {
            if (size > 0) {
                mAdapter.addData(data, map);
            }
        }
        if (size < mPageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(false);
        } else {
            mAdapter.loadMoreComplete();
        }

    }

    @Override
    public void getOrderFail(int code, String msg) {
        if (mDialog != null) {
            mDialog.stopProgressDialog();
        }
        if (mPageIndex == 1) {
            mAdapter.setEmptyView(mNotDataView);
        }
        mSwipeLayout.setRefreshing(false);
    }

    /**
     * 订单操作成功    取消或者提交
     */
    @Override
    public void orderOperationSuccess() {
        if (mOrderStatus == 1) {
            TipUtils.showToast(App.getInstance(), "确认订单成功");
        } else {
            TipUtils.showToast(App.getInstance(), "取消订单成功");
        }
        RxBus.get().post(new EventBean(Constants.EVENT_TYPE_ORDER_OPERATION));

    }

    @Override
    public void orderOperationFail(int code, String msg) {
        TipUtils.showToast(App.getInstance(), msg);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mAdapter != null) {
          mAdapter.cancelAllTimers();
        }
    }

}
